/**
 * Service for handling data loading and preprocessing
 */

// Mock function to parse CSV or Excel data
export const parseData = async (file: File): Promise<{ data: number[]; columns: string[] }> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string;
        
        // Simple parser for CSV files
        // In a real application, you'd use a proper CSV/Excel parser
        if (file.name.endsWith('.csv')) {
          const lines = content.split('\n');
          const headers = lines[0].split(',').map(h => h.trim());
          
          // Just extract the first column with numbers for this demo
          const firstColumn: number[] = [];
          for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (line) {
              const columns = line.split(',');
              const value = parseFloat(columns[0]);
              if (!isNaN(value)) {
                firstColumn.push(value);
              }
            }
          }
          
          resolve({ data: firstColumn, columns: headers });
        } else {
          // For Excel files, in a real app you'd use a library like xlsx
          // Here we'll just mock some data
          const mockLength = 200;
          const mockData = Array.from({ length: mockLength }, () => 
            Math.floor(Math.random() * 10)
          );
          const mockColumns = ['Value', 'Timestamp', 'Category'];
          
          resolve({ data: mockData, columns: mockColumns });
        }
      } catch (error) {
        reject(new Error('Failed to parse file'));
      }
    };
    
    reader.onerror = () => {
      reject(new Error('Failed to read file'));
    };
    
    if (file.name.endsWith('.csv')) {
      reader.readAsText(file);
    } else {
      // For Excel, we'd handle it differently in a real app
      // Here we're just resolving with mock data
      setTimeout(() => {
        const mockLength = 200;
        const mockData = Array.from({ length: mockLength }, () => 
          Math.floor(Math.random() * 10)
        );
        const mockColumns = ['Value', 'Timestamp', 'Category'];
        
        resolve({ data: mockData, columns: mockColumns });
      }, 500);
    }
  });
};

// Preprocess data for model input (creates sequences)
export const preprocessData = (
  data: number[], 
  sequenceLength: number, 
  startRow: number, 
  endRow: number
): { 
  features: number[][]; 
  labels: number[]; 
  diffFeatures: number[][];
} => {
  // Get the subset of data based on startRow and endRow
  const subset = data.slice(startRow - 1, endRow);
  
  // Calculate differences for the diff feature
  const diffs = subset.slice(1).map((val, i) => (val - subset[i]) % 10);
  
  const features: number[][] = [];
  const diffFeatures: number[][] = [];
  const labels: number[] = [];
  
  // Create sliding window of sequences
  for (let i = 0; i <= subset.length - sequenceLength - 1; i++) {
    const sequence = subset.slice(i, i + sequenceLength);
    const diffSequence = [0, ...diffs.slice(i, i + sequenceLength - 1)];
    const label = subset[i + sequenceLength];
    
    features.push(sequence);
    diffFeatures.push(diffSequence);
    labels.push(label % 10); // We're interested in predicting the digit (0-9)
  }
  
  return { features, diffFeatures, labels };
};

// Split data into training and validation sets
export const splitData = <T,>(data: T[], valRatio = 0.2): [T[], T[]] => {
  const splitIndex = Math.floor(data.length * (1 - valRatio));
  return [
    data.slice(0, splitIndex), // Training set
    data.slice(splitIndex)     // Validation set
  ];
};